<template>
  <div class="h-screen flex flex-col bg-gray-50">
    <!-- 顶部导航栏 -->
    <header class="bg-white shadow-sm border-b flex items-center px-4 py-3">
      <button @click="goBack" class="mr-3">
        <svg class="w-6 h-6 text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7" />
        </svg>
      </button>
      <div class="flex items-center flex-1">
        <div class="w-8 h-8 bg-gradient-to-br from-blue-500 to-indigo-600 rounded-full flex items-center justify-center">
          <svg class="w-4 h-4 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z" />
          </svg>
        </div>
        <div class="ml-3">
          <h1 class="text-lg font-semibold text-gray-900">AI超级智能体</h1>
          <p class="text-xs text-green-500">在线</p>
        </div>
      </div>
      <button @click="startNewConversation" class="ml-2">
        <svg class="w-6 h-6 text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
        </svg>
      </button>
    </header>

    <!-- 聊天区域 -->
    <main class="flex-1 overflow-hidden">
      <!-- 欢迎界面 -->
      <div v-if="messages.length === 0" class="h-full flex flex-col items-center justify-center p-6 text-center">
        <div class="w-20 h-20 bg-gradient-to-br from-blue-500 to-indigo-600 rounded-full flex items-center justify-center mb-4">
          <svg class="w-10 h-10 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z" />
          </svg>
        </div>
        <h2 class="text-xl font-bold text-gray-900 mb-2">AI超级智能体</h2>
        <p class="text-gray-600 text-sm leading-relaxed max-w-xs">
          我是您的AI超级助手，具备强大的推理能力和工具调用功能。可以帮您处理各种复杂任务。
        </p>
      </div>

      <!-- 聊天记录 -->
      <div v-else class="h-full overflow-y-auto px-4 py-4" ref="chatContainer">
        <div class="space-y-4">
          <div
            v-for="(message, index) in messages"
            :key="index"
            class="flex"
            :class="message.type === 'user' ? 'justify-end' : 'justify-start'"
          >
            <!-- AI消息 -->
            <div v-if="message.type === 'ai'" class="flex items-start max-w-[85%]">
              <div class="w-8 h-8 bg-gradient-to-br from-blue-500 to-indigo-600 rounded-full flex items-center justify-center mr-2 flex-shrink-0">
                <svg class="w-4 h-4 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z" />
                </svg>
              </div>
              <div class="bg-white rounded-2xl px-4 py-3 shadow-sm border border-gray-100">
                <div v-if="message.loading" class="flex space-x-1">
                  <div class="w-2 h-2 bg-gray-400 rounded-full animate-pulse"></div>
                  <div class="w-2 h-2 bg-gray-400 rounded-full animate-pulse" style="animation-delay: 0.2s"></div>
                  <div class="w-2 h-2 bg-gray-400 rounded-full animate-pulse" style="animation-delay: 0.4s"></div>
                </div>
                <MarkdownRenderer v-else :content="message.content" class="text-gray-800 text-sm leading-relaxed" />
              </div>
            </div>

            <!-- 用户消息 -->
            <div v-else class="flex items-start max-w-[85%] justify-end">
              <div class="bg-gradient-to-r from-blue-500 to-indigo-600 text-white rounded-2xl px-4 py-3 mr-2">
                <div class="text-sm leading-relaxed whitespace-pre-wrap">{{ message.content }}</div>
              </div>
              <div class="w-8 h-8 bg-gray-400 rounded-full flex items-center justify-center flex-shrink-0">
                <span class="text-white text-xs font-medium">{{ userInitial }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>

    <!-- 底部输入区域 -->
    <footer class="bg-white border-t px-4 py-3">
      <!-- 调试信息 -->
      <div v-if="debugMode" class="mb-3 p-2 bg-gray-100 rounded text-xs">
        <p>🔧 调试模式</p>
        <p>loading: {{ isLoading }}</p>
        <p>messages: {{ messages.length }}</p>
        <p>auth: {{ authStore.isAuthenticated ? '已认证' : '未认证' }}</p>
        <button @click="testConnection" class="mt-2 px-2 py-1 bg-blue-500 text-white rounded text-xs">
          测试连接
        </button>
      </div>
      
      <div class="flex items-end space-x-3">
        <div class="flex-1">
          <textarea
            v-model="inputMessage"
            @keydown="handleKeyDown"
            placeholder="请输入您想要咨询的问题..."
            class="w-full p-3 border border-gray-300 rounded-2xl resize-none focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm"
            rows="1"
            style="min-height: 44px; max-height: 120px;"
            :disabled="isLoading"
          ></textarea>
        </div>
        <button
          @click="toggleNetworkSearch"
          :class="[
            'p-3 rounded-full border transition-colors',
            networkSearch 
              ? 'bg-blue-500 text-white border-blue-500' 
              : 'bg-white text-gray-600 border-gray-300'
          ]"
          :disabled="isLoading"
          title="联网搜索"
        >
          <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
          </svg>
        </button>
        <button
          @click="isLoading ? handleAbort() : sendMessage()"
          :disabled="!isLoading && !inputMessage.trim()"
          :class="[
            'p-3 rounded-full transition-colors',
            isLoading 
              ? 'bg-red-500 text-white' 
              : inputMessage.trim() 
                ? 'bg-gradient-to-r from-blue-500 to-indigo-600 text-white'
                : 'bg-gray-300 text-gray-500'
          ]"
          aria-label="发送/结束"
        >
          <svg v-if="isLoading" class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
          </svg>
          <svg v-else class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8" />
          </svg>
        </button>
      </div>
    </footer>
  </div>
</template>

<script setup>
import { ref, computed, nextTick, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '../stores/auth'
import { createManusSSEConnection, createChat } from '../api/index'
import MarkdownRenderer from '../components/MarkdownRenderer.vue'

const router = useRouter()
const authStore = useAuthStore()

// 响应式数据
const messages = ref([])
const inputMessage = ref('')
const isLoading = ref(false)
const networkSearch = ref(false)
const showUserMenu = ref(false)
const chatContainer = ref(null)
const abortController = ref(null)
const debugMode = ref(false)
const chatId = ref('')
const uid = ref(null)

// 计算属性
const userInitial = computed(() => {
  return authStore.username ? authStore.username.charAt(0).toUpperCase() : 'U'
})

// 初始化聊天
const initChat = async () => {
  try {
    console.log('🔄 开始创建聊天会话...')
    const response = await createChat()
    console.log('🎯 CREATE响应:', response)
    
    if (!response) {
      throw new Error('create接口无响应')
    }
    
    if (response.chatId && response.id) {
      chatId.value = response.chatId
      uid.value = response.id
      console.log('✅ 设置成功 - chatId:', chatId.value, 'uid:', uid.value)
    } else if (response.id) {
      chatId.value = response.id  
      uid.value = response.id     
      console.log('⚠️ 只有id字段 - chatId:', chatId.value, 'uid:', uid.value)
    } else {
      throw new Error('响应中缺少必要字段（chatId或id）')
    }
    
  } catch (error) {
    console.error('❌ 创建聊天失败:', error)
    if (error.message?.includes('403') || error.response?.status === 403) {
      router.push('/login')
      return
    }
    chatId.value = 'test-chat-id'
    uid.value = 'test-uid'
    console.log('🔧 使用测试值 - chatId:', chatId.value, 'uid:', uid.value)
  }
}

// 方法
const goBack = () => {
  router.push('/mobile-home')
}

const startNewConversation = async () => {
  if (isLoading.value) return
  
  if (messages.value.length > 0) {
    if (confirm('确定要开始新对话吗？当前对话记录将被清除。')) {
      messages.value = []
      inputMessage.value = ''
      isLoading.value = false
      chatId.value = ''
      uid.value = null
      
      console.log('🔄 开启新对话，重新获取chatId和uid...')
      await initChat()
      console.log('新对话已开始')
    }
  } else {
    messages.value = []
    inputMessage.value = ''
    chatId.value = ''
    uid.value = null
    await initChat()
  }
}

const toggleNetworkSearch = () => {
  if (isLoading.value) return
  networkSearch.value = !networkSearch.value
}

const scrollToBottom = () => {
  nextTick(() => {
    if (chatContainer.value) {
      chatContainer.value.scrollTop = chatContainer.value.scrollHeight
    }
  })
}

const handleKeyDown = (event) => {
  if (event.key === 'Enter' && !event.shiftKey) {
    event.preventDefault()
    if (!isLoading.value && inputMessage.value.trim()) {
      sendMessage()
    }
  }
}

const sendMessage = async () => {
  if (!inputMessage.value.trim() || isLoading.value) return

  if (!chatId.value) {
    console.error('❌ 没有chatId，无法发送消息')
    return
  }
  if (!uid.value) {
    console.error('❌ 没有uid，无法发送消息')
    return
  }

  const userMessage = inputMessage.value.trim()
  inputMessage.value = ''
  
  console.log('🚀 开始发送消息:', userMessage)

  // 添加用户消息
  messages.value.push({
    type: 'user',
    content: userMessage,
    timestamp: Date.now()
  })

  // 添加AI加载消息
  const aiMessageIndex = messages.value.length
  messages.value.push({
    type: 'ai',
    content: '',
    loading: true,
    timestamp: Date.now()
  })

  scrollToBottom()
  isLoading.value = true

  try {
    console.log('📡 调用createManusSSEConnection...')

    const controller = createManusSSEConnection(
      userMessage,
      (data) => {
        // 处理接收到的数据
        console.log('📥 收到数据片段:', data)
        if (messages.value[aiMessageIndex] && messages.value[aiMessageIndex].loading) {
          messages.value[aiMessageIndex].loading = false
        }
        if (messages.value[aiMessageIndex]) {
          messages.value[aiMessageIndex].content += data
          scrollToBottom()
        }
      },
      (error) => {
        console.error('❌ SSE连接错误:', error)
        if (messages.value[aiMessageIndex]) {
          messages.value[aiMessageIndex] = {
            type: 'ai',
            content: `抱歉，发送消息时出现错误：${error.message || '网络连接问题'}。请检查网络连接或稍后重试。`,
            loading: false,
            timestamp: Date.now()
          }
        }
        isLoading.value = false
        scrollToBottom()
      },
      () => {
        // 连接完成
        console.log('✅ SSE连接完成')
        isLoading.value = false
        if (messages.value[aiMessageIndex]) {
          messages.value[aiMessageIndex].loading = false
        }
        scrollToBottom()
      }
    )
    
    // 保存控制器以便取消
    abortController.value = controller

  } catch (error) {
    console.error('💥 发送消息失败:', error)
    if (messages.value[aiMessageIndex]) {
      messages.value[aiMessageIndex] = {
        type: 'ai',
        content: `抱歉，发送消息时出现错误：${error.message || '未知错误'}。请稍后重试。`,
        loading: false,
        timestamp: Date.now()
      }
    }
    isLoading.value = false
    scrollToBottom()
  }
}

const handleAbort = () => {
  if (abortController.value && typeof abortController.value.abort === 'function') {
    abortController.value.abort()
  }
  isLoading.value = false
  // 找到最后一个AI消息，结束loading并加提示
  const lastAiMsg = [...messages.value].reverse().find(m => m.type === 'ai' && m.loading)
  if (lastAiMsg) {
    lastAiMsg.loading = false
    if (!lastAiMsg.content || !lastAiMsg.content.trim()) {
      lastAiMsg.content = '[回复已终止]'
    } else {
      lastAiMsg.content += '\n[回复已终止]'
    }
  }
}

const toggleDebug = () => {
  debugMode.value = !debugMode.value
}

const testConnection = () => {
  console.log('🧪 开始测试连接...')
  
  const testMessage = '你好，这是一个连接测试'
  
  createManusSSEConnection(
    testMessage,
    (data) => {
      console.log('✅ 测试连接成功，收到数据:', data)
      alert('连接测试成功！')
    },
    (error) => {
      console.error('❌ 测试连接失败:', error)
      alert(`连接测试失败: ${error.message || '未知错误'}`)
    },
    () => {
      console.log('✅ 测试连接完成')
    }
  )
}

onMounted(() => {
  initChat()
  scrollToBottom()
})

onUnmounted(() => {
  isLoading.value = false
})
</script> 